package biz.ezcom.spring.jdbc.dao.impl;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import org.dbunit.DatabaseUnitException;
import org.dbunit.database.DatabaseConnection;
import org.dbunit.database.IDatabaseConnection;
import org.dbunit.database.QueryDataSet;
import org.dbunit.dataset.IDataSet;
import org.dbunit.dataset.xml.FlatDtdDataSet;
import org.dbunit.dataset.xml.FlatXmlDataSet;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

public class DBToXml {
    public static final String DEFAULT_DIR = "./document/data/";
    
    private Connection connection;

    @BeforeClass
    public static void beforeClass() throws ClassNotFoundException {
        Class.forName("com.mysql.jdbc.Driver");
    }

    @Before
    public void before() throws SQLException {
        connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/spring_jdbc", "root", "root");
    }

    @After
    public void after() throws SQLException {
        connection.close();
    }

    @Test
    public void testTableToXml() throws FileNotFoundException, IOException, DatabaseUnitException {
        IDatabaseConnection dbUnitConnection = new DatabaseConnection(connection);
        QueryDataSet dataSet = new QueryDataSet(dbUnitConnection);
        dataSet.addTable("user");
        FlatXmlDataSet.write(dataSet, new FileOutputStream(DEFAULT_DIR + "table_user.xml"));
    }
    
    @Test
    public void testTablePartToXml() throws FileNotFoundException, IOException, DatabaseUnitException {
        IDatabaseConnection dbUnitConnection = new DatabaseConnection(connection);
        QueryDataSet dataSet = new QueryDataSet(dbUnitConnection);
        dataSet.addTable("user", "select * from user where id = 1;");
        FlatXmlDataSet.write(dataSet, new FileOutputStream(DEFAULT_DIR + "table_user_part.xml"));
    }
    
    @Test
    public void testSchemaToXml() throws DatabaseUnitException, SQLException, FileNotFoundException, IOException {
        IDatabaseConnection dbUnitConnection = new DatabaseConnection(connection);
        IDataSet dataSet = dbUnitConnection.createDataSet();  
        FlatXmlDataSet.write(dataSet,new FileOutputStream(DEFAULT_DIR + "schema_dbunit.xml"));  
        FlatDtdDataSet.write(dataSet,new FileOutputStream(DEFAULT_DIR + "schema_dbunit.dtd"));  
    }
    
    
}
